﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Core.Extensions;
using App.Data;
using System.IO;

public partial class Pages_Private_PropertyForRentChange : BasePage
{
    private int _ID = 0;
    private bool _IsEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropDownLists();
            BindPropertyToRentInfo();
            ShowSuccessMessage();
        }
    }
    /// <summary>
    /// Bindis the Page Initialization Variables
    /// </summary>
    protected void BindPageInfo()
    {
        _ID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        if (_ID > 0)
        {
            _IsEditMode = true;
            h4Heading.InnerHtml = "Edit Property for Rent";
        }
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }

    /// <summary>
    /// Binds Dropdownlists for the initial request.
    /// </summary>
    protected void BindDropDownLists()
    {
        BindDropdownList.Countries(ddlCountry);        
        BindDropdownList.RentStatuses(ddlRentStatusID);
        BindDropdownList.RentTypes(ddlRentTypeID);
    }
    protected void ShowSuccessMessage()
    {
        if (String.Compare(WebUtil.GetQueryStringInString(AppConstants.QueryString.SUCCESS_MESSAGE), "True", false) == 0)
            WebUtil.ShowMessageBox(divMessage, "Property Rent Information Saved Successfully.", false);
    }
    /// <summary>
    /// Binds PropertyToRent Info Requested through Query Strings
    /// </summary>
    protected void BindPropertyToRentInfo()
    {
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            PropertyToRent entity = context.PropertyToRents.Include("Zone.City.Country").FirstOrDefault(P => P.ID == _ID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                ddlRentTypeID.SetSelectedItem(entity.RentTypeID.ToString());
                ddlRentStatusID.SetSelectedItem(entity.RentStatusID.ToString());
                //ddlCompanyID.SetSelectedItem(entity.CompanyID.ToString());
                txtSize.Text = entity.Size.ToString();
                txtExpireDate.Text = entity.ExpireDate.ToString(ConfigReader.CSharpCalendarDateFormat);
                txtNoOfBeds.Text = entity.NoOfBeds.ToString();
                txtMonthlyRent.Text = entity.MonthlyRent.ToString();
                txtServiceCharge.Text = entity.ServiceCharge.ToString();
                ///Set Selected Zones
                ddlCountry.SetSelectedItem(entity.Zone.City.CountryID.ToString());
                ddlCountry_SelectedIndexChanged(ddlCountry, EventArgs.Empty);

                ddlCityID.SetSelectedItem(entity.Zone.CityID.ToString());
                ddlCityID_SelectedIndexChanged(ddlCityID, EventArgs.Empty);
                
                ddlZoneID.SetSelectedItem(entity.ZoneID.ToString());
                
                txtAddress.Text = entity.Address;
                chkHasParking.Checked = entity.HasParking;
                chkHasGenerator.Checked = entity.HasGenerator;
                chkHasLift.Checked = entity.HasLift;
                txtOtherUtility.Text = entity.OtherUtility;
                //txtImage1.Text = entity.Image1;
                txtRemark.Text = entity.Remark;
                chkIsActive.Checked = entity.IsActive;
                //txtVerificationKey.Text = entity.VerificationKey;

                if (!entity.ThumbImage.IsNullOrEmpty())
                {
                    divImageThumb.InnerHtml = String.Format("<img src='{0}/{1}' alt='Property Thumb' title='Property Thumb'/>", AppConstants.FOR_RENT_PROPERTY_FILES, entity.ThumbImage);
                    divImageThumb.Visible = true;
                }
            }
        }
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested PropertyToRent was not found.", true);
    }
    protected void SavePropertyToRent()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        PropertyToRent entity = null;
        if (_IsEditMode)
            entity = context.PropertyToRents.FirstOrDefault(P => P.ID == _ID); //dao.GetByID(_ID);        
        else
        {
            entity = new PropertyToRent();
            entity.Created = DateTime.Now;
            entity.IsDeleted = false;
            entity.VerificationKey = System.Guid.NewGuid();
            context.AddToPropertyToRents(entity);
        }

        entity.RentTypeID = ddlRentTypeID.SelectedValue.ToInt();
        entity.RentStatusID = ddlRentStatusID.SelectedValue.ToInt();
        entity.CompanyID = SessionCache.CurrentUser.CustomerID; //ddlCompanyID.SelectedValue.ToInt();
        entity.ExpireDate = txtExpireDate.Text.ToDateTime(ConfigReader.CSharpCalendarDateFormat);
        entity.Size = txtSize.Text.ToInt();
        entity.NoOfBeds = txtNoOfBeds.Text.ToInt();
        entity.MonthlyRent = txtMonthlyRent.Text.ToInt();
        entity.ServiceCharge = txtServiceCharge.Text.ToInt();
        //entity.CityID = ddlCityID.SelectedValue.ToInt();
        entity.ZoneID = ddlZoneID.SelectedValue.ToInt();
        entity.Address = txtAddress.Text;
        entity.HasParking = chkHasParking.Checked;
        entity.HasGenerator = chkHasGenerator.Checked;
        entity.HasLift = chkHasLift.Checked;
        entity.OtherUtility = txtOtherUtility.Text;
        //entity.Image1 = txtImage1.Text;
        entity.Remark = txtRemark.Text;
        entity.Modified = DateTime.Now;
        entity.IsActive = chkIsActive.Checked; 
        entity.ModifiedBy = SessionCache.CurrentUser.ID;
        context.SaveChanges();
        ///Save File
        
        SavePropertyIamge(context, entity);

        WebUtil.ShowMessageBox(divMessage, "PropertyToRent Saved Successfully.", false);
    }

    protected void SavePropertyIamge(BtcHousingEntities context, PropertyToRent entity)
    {
        if (fuImage.HasFile)
        {
            String rentImageDirectory = Server.MapPath(AppConstants.FOR_RENT_PROPERTY_FILES);
            ///Delete Existing File
            if (_IsEditMode && !entity.LargeImage.IsNullOrEmpty())
            {                
                String existingFile = Path.Combine(rentImageDirectory, entity.LargeImage);
                ///Delete Large
                if (File.Exists(existingFile))
                    File.Delete(existingFile);
                ///Delete Thumb
                existingFile = Path.Combine(rentImageDirectory, entity.ThumbImage);
                if (File.Exists(existingFile))
                    File.Delete(existingFile);
            }
            String inputFile = Path.Combine(rentImageDirectory, String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuImage.FileName)));
            String outputFile = Path.Combine(rentImageDirectory, String.Format("{0}_Thumb{1}", Path.GetFileNameWithoutExtension(inputFile), Path.GetExtension(inputFile)));
            
            if (!Directory.Exists(rentImageDirectory))
                Directory.CreateDirectory(rentImageDirectory);
            ///Save the file
            fuImage.SaveAs(inputFile);
            ///Generate the Thumbnail
            WebUtil.GenerateThumbnail(inputFile, outputFile, 132, false);

            entity.ThumbImage = Path.GetFileName(outputFile);
            entity.LargeImage = Path.GetFileName(inputFile);
            context.SaveChanges();
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SavePropertyToRent();
            Response.Redirect(String.Format("{0}?{1}=True", Request.Url.AbsolutePath, AppConstants.QueryString.SUCCESS_MESSAGE));
            return;
        }
    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        Response.Redirect("/Pages/Private/PropertyForRentList.aspx");
        return;
    }
    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        String countryID = ddlCountry.SelectedValue;
        if (!countryID.IsNullOrEmpty())
            BindDropdownList.Cities(ddlCityID, countryID.ToInt());
    }
    protected void ddlCityID_SelectedIndexChanged(object sender, EventArgs e)
    {
        String cityID = ddlCityID.SelectedValue;
        if (!cityID.IsNullOrEmpty())
            BindDropdownList.Zones(ddlZoneID, cityID.ToInt());
    }
    protected void cvImage_OnServerValidate(object sender, ServerValidateEventArgs e)
    {
        if (fuImage.HasFile)
        {
            if (WebUtil.IsValidImageFile(fuImage.PostedFile))
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        else
            e.IsValid = true;
    }
}